import { defineStore } from 'pinia'
import { UserInfo } from '@/types/commonType'
import { ref } from 'vue'
import { UserInfoResponseData } from '@/services/user/type'
import { getUserInfoAPI } from '@/services/user/user'

// 用户模块
export const useUserStore = defineStore(
  'user',
  () => {
    /**
     * token 相关
     */
    const token = ref<string>('')
    // 存储token
    const setToken = (newVal: string) => {
      token.value = newVal
    }
    // 删除token
    const removeToken = () => {
      token.value = ''
    }

    /**
     * user 相关
     */
    const userInfo = ref<UserInfo>({} as UserInfo)
    // 存储userInfo
    const getUserInfo = async () => {
      const res: UserInfoResponseData = await getUserInfoAPI()
      userInfo.value = res.data
      return Promise.resolve()
    }
    // 删除userInfo
    const removeUserInfo = () => {
      userInfo.value = {} as UserInfo
    }

    return {
      token,
      setToken,
      removeToken,
      userInfo,
      getUserInfo,
      removeUserInfo
    }
  },
  {
    persist: {
      paths: ['token', 'userInfo']
    }
  }
)
